const mongoose = require('mongoose')
const bcrypt = require('bcrypt-nodejs')
const config = require('../config')
const glob = require('glob')
const { resolve } = require('path')

mongoose.Promise = global.Promise

exports.initDefaultUser = async () => {
  const User = mongoose.model('user')
  const Group = mongoose.model('group')
  
  // 设置默认账户
  let userDefault = await User.findOne({
    nickname: config.userDefault.nickname 
  })
  
  if(!userDefault) {
    // 密码加盐
    const salt = bcrypt.genSaltSync(10)
    const nickname = config.userDefault.nickname
    const password = bcrypt.hashSync(config.userDefault.password, salt);
    const email = config.userDefault.email

    userDefault = await new User({
      nickname,
      password,
      email
    })

    let initGroup = await new Group({
      nickname: `${nickname}的官方群`,
      creator: userDefault._id
    })

    userDefault.groups.push(initGroup._id)
    initGroup.members.push(userDefault._id)

    await userDefault.save()
    await initGroup.save()
  }
}

// 加载所有Schema
exports.initAllSchema = () => {
  glob.sync(resolve(__dirname, './schemas', '**/*.js')).forEach(require)
}

exports.connectDatabase = () => {
  let maxConnectTimes = 0

  return new Promise((resolve, reject) => {

    mongoose.connect(config.db)

    mongoose.connection.on('disconnected', () => {
      maxConnectTimes++
      if (maxConnectTimes < 5) {
        mongoose.connect(config.db)
      } else {
        if (reject) {
          reject(err)
        } else {
          throw new Error('数据库断开了~0.0!')
        }
      }
    })

    mongoose.connection.on('error', err => {
      maxConnectTimes++
      if (maxConnectTimes < 5) {
        mongoose.connect(config.db)
      } else {
        if (reject) {
          reject(err)
        } else {
          throw new Error('数据库挂了~0.0!')
        }
      }
    })

    mongoose.connection.once('open', () => {
      console.log('(0.0)数据库连接成功')
      resolve()
    })
    
  })
}
